package com.nulldev.util.web.HttpClient.providers.websockets;

import java.io.IOException;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.web.HttpClient.HttpClient;

public class WebSocketsDemo {

	public static void main(String[] args) throws Exception {
		final String URL = "wss://echo.websocket.org";
		final HttpWebSocketRequest w = HttpClient.getSocket();
		JVM.println("Builder provided by: " + w);
		w.url(URL);
		final HttpWebSocket ws = w.make();
		JVM.println("Socket provided by: " + ws);
		final boolean r = ws.registerListener(new WebSocketListener() {

			@Override
			public void onMessage(Message message) {
				JVM.println("message: " + message);
			}

			@Override
			public void onError(Throwable t) {
				throw new RuntimeException(t);
			}

			@Override
			public void onConnect() {
				JVM.println("Connected to " + URL + ".");
				ws.send("Hello world!");
				try {
					Thread.sleep(5000L);
					try {
						ws.close();
					} catch (IOException e) {
					}
				} catch (Exception e) {
				}
			}

			@Override
			public void onClosed() {
				JVM.println("Connection closed.");
			}
		});
		JVM.println("r: " + r);
	}
}
